var express = require('express');

var bodyParser = require('body-parser')
var echarts = require("echarts");
const { createCanvas } = require("canvas");

var app = express();
app.use((req, res, next) => { // 要删除编码,这是body-parser的bug,下面的代码是删除编码,加上下面的代码一定要放在 `express()`下面第一句
    var encoding = req.headers['content-encoding'];
    if (encoding === 'UTF-8'  || encoding === 'utf-8') {
        delete req.headers['content-encoding'];
    }

    next();
});
 
echarts.setPlatformAPI(() => {
    return createCanvas();
});
 
function renderChart(data) {
   // const canvas = createCanvas(data.width, data.height);
   // 当不编写canvas元素的高宽时，默认宽是300，高是150,不设置会报错
	const canvas = createCanvas(600,400);
    const chart = echarts.init(canvas);
 
    chart.setOption(data);
    return canvas;
}
 
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
 
app.post('/genEchartsImage', function (req, res) {
    res.writeHead(200, {
        "Content-Type": "image/png"
    });
    console.log(req.url);
    res.write(renderChart(req.body).toBuffer("image/png"));
    res.end();
})
 
var server = app.listen(8602, function () {
    console.log('服务运行在http://0.0.0.0:8602/genEchartsImage')
})


